<?php

namespace api\libs\swoft\ifc;

use api\libs\swoft\core\SwoftCore;
use api\modules\app\resource\UserResource;
use yii\helpers\Json;
use Yii;

/**
 * 客户端服务接口基类
 * @author Johnson
 * @date 2018-05-22
 */
abstract class SwoftClient {

    /**
     * @var SwoftCore
     */
    private $_swoftService;
    private $_config;
    private static $_instances = array();

    private function __construct() {

    }

    public static function instance($config) {
        $className = get_called_class();
        if (!array_key_exists($className, self::$_instances))
            self::$_instances[$className] = new $className();

        self::$_instances[$className]->initConfig($config);
        return self::$_instances[$className];
    }

    private function initConfig($config) {
        if (empty($config))
            throw new CHttpException(500, 'Swoft 配置文件错误！');
        $this->_config = $config;
        $this->_swoftService = new SwoftCore($config['key'], $config['secret'], $config['host']);
    }

    /**
     * 发送请求
     * @param array $option 参数
     */
    protected function sendRequest($options) {
        $response = $this->_swoftService->auth($options);
        $result = false;
        switch ($response->status) {
            case 200: //请求成功，返回用户信息
            case 404:
            case 410:
            case 401:
                $result = Json::decode($response->body, false);
                break;
            case 403: //请求成功，返回用户信息
                $result = Json::decode($response->body, false);
                break;
            case 500:
            default:
                break;
        }
        if ($result === false) {
            return ['code' => 500, 'message' => 'Internal Error','status' => \api\components\helpers\Constant::API_STATUS_FAILED];
        } else {
            return $result;
        }
    }

    /**
     * 添加资源
     * @param unknown_type $res
     */
    public function resource($res) {
        return $this;
    }

    public function getBaseUri() {
        return $this->_config['baseuri'];
    }

    public function getConfig() {
        return $this->_config;
    }

    //
    protected function convertParams($params){
        foreach($params as $key => $value){
            if(is_array($value)){
                foreach($value as $k => $v){
                    $new_key = $key . "[$k]";
                    $params[$new_key] = $v;
                }
                unset($params[$key]);
            }
        }
        return $params;
    }

}
